#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string_view>

using namespace std;
#include "SysYLexer.h"
#include "SysYParser.h"
using namespace antlr4;
#include "PassManager.h"
#include "SysYIRGenerator.h"
#include "ToLLVM.h"

using namespace sysy;

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        cerr << "Usage: " << argv[0] << "inputfile\n";
        return EXIT_FAILURE;
    }
    ifstream fin(argv[1]);
    if (not fin)
    {
        cerr << "Failed to open file " << argv[1];
        return EXIT_FAILURE;
    }

    // 展开宏starttime() stoptime()
    string start = "starttime()", stop = "stoptime()";
    stringstream ss;
    int lineNum = 1;
    string lineContent;

    while (getline(fin, lineContent))
    {
        if (auto pos = lineContent.find(start); pos != string::npos)
        {
            ss << lineContent.substr(0, pos) << "_sysy_starttime(" << lineNum << ")"
               << lineContent.substr(pos + start.length()) << '\n';
        }
        else if (pos = lineContent.find(stop); pos != string::npos)
        {
            ss << lineContent.substr(0, pos) << "_sysy_stoptime(" << lineNum << ")"
               << lineContent.substr(pos + stop.length()) << '\n';
        }
        else
        {
            ss << lineContent << '\n';
        }
        lineNum++;
    }

    string src = ss.str();
    string_view srcView = src;

    ANTLRInputStream input(srcView);
    SysYLexer lexer(&input);
    CommonTokenStream tokens(&lexer);
    SysYParser parser(&tokens);
    auto compUnit = parser.compUnit();

    SysYIRGenerator generator;
    auto module = generator.visitCompUnit(compUnit);

    auto modulep = any_cast<Module *>(module);

    auto pm = PassManager();
    modulep = pm.runPasses(modulep);

    LLVMgen llvmgen;
    cout << llvmgen.transform(modulep);

    return EXIT_SUCCESS;
}
